package com.hfzy.ihk.web.ivr.biz;

import com.alibaba.fastjson.JSON;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.facade.ivr.vo.FreeswitchCallState;
import com.hfzy.ihk.web.ivr.constant.PublicConfig;
import com.hfzy.ihk.web.ivr.context.DisruptorInitBean;
import com.hfzy.ihk.web.ivr.context.EventSocketInitBean;
import com.hfzy.ihk.web.ivr.support.callin.event.FreeswitchCallStateEvent;
import com.hfzy.ihk.web.ivr.support.disruptor.DisruptorSupport;
import com.lmax.disruptor.RingBuffer;
import org.freeswitch.esl.client.transport.event.EslEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/6/17.
 */
@Lazy
@Component
public class FreeswitchAsrCallSpeakStateBiz extends DisruptorSupport<FreeswitchCallState, FreeswitchCallStateEvent> {

    private static final Logger logger = LoggerFactory.getLogger(FreeswitchAsrCallSpeakStateBiz.class);

    @Autowired
    EventSocketInitBean eslInitBean;

    @Override
    protected RingBuffer<FreeswitchCallStateEvent> useRingBuffer(FreeswitchCallState data) {

        int index = 0;
        RingBuffer ringBuffer = null;

        String useType = "ivr --> Freeswitch单呼说话中间状态";

        String sessionId = data.getEvent().getEventHeaders().get("Channel-Call-UUID");

        if(StringTools.isEmpty(sessionId)){
            sessionId = data.getEvent().getEventHeaders().get("sessionId");
        }
        if(StringTools.isEmpty(sessionId)){
            sessionId = data.getEvent().getEventHeaders().get("session_id");
        }

        if (StringTools.isEmpty(sessionId))
            return null;

        //session 做hash 判断应该进哪一个队列
        index = sessionId.hashCode() % PublicConfig.ALIYUN_CALL_STATE_BUFFER_NUM_SIZE;

        ringBuffer = DisruptorInitBean.getRingBufferFreeswitchAsrCallSpeakState(Math.abs(index));

        checkRingBufferUse(ringBuffer, useType);
        return ringBuffer;

    }

    /**
     * 处理状态消息
     *
     * @param
     */

    public void dealAsrCallSpeakState(EslEvent event) {

        FreeswitchCallState freeswitchCallState = new FreeswitchCallState(event);

        if (StringTools.isEmpty(freeswitchCallState)) {
            return;
        }

        logger.debug("putInRingBuffer:{}", JSON.toJSONString(freeswitchCallState));
        putInRingBuffer(freeswitchCallState);

    }

    /**
     * 执行freeswicth api命令
     * @param bgapi
     * @param arg
     */
    public void sendAsyncApiCommand(String bgapi,String arg){
        try {
            logger.info("执行freeswitch api命令bgapi:{},arg:{}",bgapi,arg);
            eslInitBean.getClient().sendBackgroundApiCommand(bgapi, arg);
        }catch (Exception e){
            logger.error("执行freeswitch api命令bgapi:{},arg:{},异常，异常信息：{}",bgapi,arg,e);
        }
    }
}
